#include "UdpServer.hpp"
#include <memory>
#include <cstdio>
#include <vector>

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " port[1024-65535]\n" << std::endl;
}

std::string handler(const std::string& str, const std::string clientip, uint16_t clientport)
{
    std::cout << "[" << clientip << ": " << clientport << "]# " << str;
    std::string res = "Server get a message: " + str;
    std::cout << res << std::endl;
    return res;
}

bool SafeCheck(const std::string& cmd)
{
    std::vector<std::string> key_words = {
        "rm",
        "mv",
        "cp",
        "kill",
        "sudo",
        "unlink",
        "uninstall",
        "yum",
        "top",
        "while",
        "touch",
        "for"
    };
    for(auto& word : key_words) 
    {
        auto pos = cmd.find(word);
        if(pos != std::string::npos) return false;
    }
    return true;
}

std::string ExcuteCommand(const std::string& cmd)
{
    std::cout << "get a request cmd: " << cmd << std::endl;
    if(!SafeCheck(cmd)) return "You are a bad-man!\n";

    FILE* fp = popen(cmd.c_str(), "r");
    if(fp == nullptr)
    {
        perror("popen");
        return "error";
    }
    std::string ret;
    char buffer[4096];
    while(true)
    {
        char* ok = fgets(buffer, sizeof(buffer), fp);
        if(ok == nullptr) break;
        ret += buffer;
    }

    pclose(fp);
    return ret;
}

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    uint16_t port = std::stoi(argv[1]);

    std::unique_ptr<UdpServer> svr(new UdpServer(port));
    svr->Init();
    svr->Run();

    return 0;
}
